<template>
  <!-- <h1>
    div.middle内移动坐标x:{{ elementX }}，y:{{ elementY }},是否在盒子外移动：{{
      isOutside
    }}
  </h1> -->

  <div class="goods-image">
    <!-- 放大镜 -->
    <div
      class="large"
      v-show="!isOutside"
      :style="[
        {
          backgroundImage: `url(${list[currIndex]})`,
          backgroundPosition: `${bg.x}px ${bg.y}px`,
        },
      ]"
    ></div>
    <div class="middle" ref="target">
      <img :src="list[currIndex]" alt="" />
      <!-- 蒙层滑块 -->
      <div
        v-show="!isOutside"
        class="layer"
        :style="{ left: `${pos.left}px`, top: `${pos.top}px` }"
      ></div>
    </div>
    <ul class="small">
      <li v-for="(img, i) in list" :key="i" @mouseenter="currIndex = i">
        <img :src="img" alt="" />
      </li>
    </ul>
  </div>
</template>
<script>
import { ref, watch } from 'vue'
import { useMouseInElement } from '@vueuse/core'
export default {
  name: 'GoodsImage',
  props: {
    list: {
      type: Array,
      default: () => []
    }
  },
  setup () {
    const currIndex = ref(0)
    // 放大镜实现
    // 前置知识：浏览器坐标系从左上角开发（x：0，y：0）
    // 1.获取鼠标移动的坐标
    // target 限定鼠标移动范围
    const target = ref(null)
    const pos = ref({ left: 0, right: 0 })
    //  蒙层图片放大
    const bg = ref({ x: 0, y: 0 })
    const { elementX, elementY, isOutside } = useMouseInElement(target)
    // 监控蒙层移动
    watch([elementX, elementY], () => {
      // x轴
      if (elementX.value < 100) {
        pos.value.left = 0
      } else if (elementX.value > 300) {
        pos.value.left = 200
      } else {
        pos.value.left = elementX.value - 100
      }
      // y轴
      if (elementY.value < 100) {
        pos.value.top = 0
      } else if (elementY.value > 300) {
        pos.value.top = 200
      } else {
        pos.value.top = elementY.value - 100
      }
      // 计算背景图放大
      bg.value.x = -pos.value.left * 2
      bg.value.y = -pos.value.top * 2
    })

    return { bg, currIndex, target, elementX, elementY, isOutside, pos }
  }
}
</script>
<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    z-index: 500;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    // <!--配套样式 -- >
    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0, 0, 0, 0.2);
      left: 0;
      top: 0;
      position: absolute;
    }
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
